//
//  LWNetworkTools.swift
//  Swift网络工具类封装
//
//  Created by huanglinwang on 16/9/21.
//  Copyright © 2016年 Linwang. All rights reserved.
//

import UIKit
import AFNetworking

//请求类型

enum requestType {
    case GET
    case POST
}


class LWNetworkTools: AFHTTPSessionManager {

    //单例
    
    
    static let sharedTools: LWNetworkTools = {
       let tools =  LWNetworkTools()
        //添加可以接受的响应数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
  
    //封装的AFN方法
    fileprivate func request(type: requestType, url: String ,parame: Any?, callBack: (@escaping (Any?, Error?)->()) ){
        
        if type == .GET {
            get(url, parameters: parame, progress: nil, success: { (_, response) in
                callBack(response, nil)
            }) { (_, error) in
                callBack(nil, error)
            }
        }else{
            post(url, parameters: parame, progress: nil, success: { (_, response) in
                callBack(response, nil)
                }, failure: { (_, error) in
                    callBack(nil, error)
            })
        }
    }
    
}
// OAuth 登陆相关接口
extension LWNetworkTools {
    
    //根据code获取accesstoken
    func requestAccessToken(code: String, callBack:@escaping ((Any?,Error?)->())) {
        //请求接口地址
        let url = "https://api.weibo.com/oauth2/access_token"
        let parame = [
            "client_id": WeiboAppKey,
            "client_secret": WeiboAppSecret,
            "grant_type" : "authorization_code",
            "code": code,
            "redirect_uri" : WeiboRedirect_Uri
        ]
        request(type: .POST, url: url, parame: parame, callBack: callBack)
    }
    
    
    
    
    //通过accessToken 获取用户信息
    func requestUserInfo(accessToken: String,uid: Int64,callBack:@escaping ((Any?, Error?) -> ())) {
        
        let url = "https://api.weibo.com/2/users/show.json"
        let params: [String:Any] = [
            "access_token" :accessToken,
            "uid":uid,
        ]
        
        request(type: .GET, url: url, parame: params, callBack: callBack)
        
    }
    
    
}

//获取获取当前登录用户及其所关注（授权）用户的最新微博
extension LWNetworkTools{

    func requestStatuses(accessToken: String, maxId: Int64, sinceId: Int64, callBack: @escaping (Any?, Error?)->()) {

        //url
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //参数
        let params: [String : Any] = [
            "access_token" : accessToken,
            "max_id": maxId,
            "since_id": sinceId
        ]
        //获取URL路径
        print(url+"?access_token=\(accessToken)")
        
        //执行网络请求
        request(type: .GET, url: url, parame: params, callBack: callBack)
    }
    
}


































